﻿using CCWin.SkinControl;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class 发送到 : Form
    {
        // 从主窗体获取的信息
        private string _serverIp;
        private int _serverPort;
        private string _username;
        private string _password;
        private List<string> _topics;
        private IMqttClient _mqttClient;

        public 发送到(string ip, int port, string username, string password, List<string> topics)
        {
            InitializeComponent();
            // 保存主窗体传递的信息
            _serverIp = ip;
            _serverPort = port;
            _username = username;
            _password = password;
            _topics = topics;

            // 初始化界面
            InitializeUI();

        }

        /// <summary>
        /// 初始化界面
        /// </summary>
        private void InitializeUI()
        {
            // 初始化主题下拉框 - 使用设计器生成的控件名称
            if (cbxtext != null)
            {
                cbxtext.Items.Clear();
                foreach (var topic in _topics)
                {
                    cbxtext.Items.Add(topic);
                }
                if (cbxtext.Items.Count > 0)
                {
                    cbxtext.SelectedIndex = 0;
                }
            }

            // 调试信息：显示传递的主题数量
            if (rtb内容 != null)
            {
                rtb内容.Text = $"主题 (已加载 {_topics.Count} 个)";
            }
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 使用设计器生成的控件名称，无需通过Controls查找

                // 验证输入
                if (cbxtext == null || string.IsNullOrEmpty(cbxtext.Text))
                {
                    MessageBox.Show("请选择主题", "参数缺失", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (rtb内容 == null || string.IsNullOrEmpty(rtb内容.Text))
                {
                    MessageBox.Show("请输入消息内容", "参数缺失", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 显示发送状态
                skinButton1.Text = "正在发送...";
                skinButton1.Enabled = false;

                // 创建MQTT客户端
                if (_mqttClient == null)
                {
                    var factory = new MqttFactory();
                    _mqttClient = factory.CreateMqttClient();
                }

                // 连接到服务器
                if (!_mqttClient.IsConnected)
                {
                    var options = new MqttClientOptionsBuilder()
                        .WithTcpServer(_serverIp, _serverPort)
                        .WithCredentials(_username, _password)
                        .WithClientId($"ServerSender_{Guid.NewGuid().ToString().Substring(0, 8)}")
                        .WithCleanSession()
                        .Build();

                    await _mqttClient.ConnectAsync(options);
                }

                // 创建消息
                var message = new MqttApplicationMessageBuilder()
                    .WithTopic(cbxtext.Text)
                    .WithPayload(rtb内容.Text)
                    .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // 使用默认QoS 1
                    .WithRetainFlag(false)
                    .Build();

                // 发布消息
                await _mqttClient.PublishAsync(message);

                // 显示成功状态
                skinButton1.Text = "发送成功！";
                skinButton1.BackColor = Color.LightGreen;

                // 清空消息框
                rtb内容.Clear();

                // 延迟恢复按钮状态
                await Task.Delay(2000);
                skinButton1.Text = "发送";
                skinButton1.BackColor = Color.FromArgb(255, 128, 128);
                skinButton1.Enabled = true;
            }
            catch (Exception ex)
            {
                // 显示错误信息
                skinButton1.Text = "发送失败";
                skinButton1.BackColor = Color.LightCoral;
                skinButton1.Enabled = true;

                MessageBox.Show($"发送失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 延迟恢复按钮状态
                await Task.Delay(2000);
                skinButton1.Text = "发送";
                skinButton1.BackColor = Color.FromArgb(255, 128, 128);
            }
        }
    
    }
}

